package com.fortune.rainshinecommon.alioss;

import com.aliyun.oss.OSSClient;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

/**
 * @author wcy
 * @description oss文件上传工具
 * @createDate 2018/4/12
 * @updateBy
 * @updateDate
 */
public class OssUtils {
    private static final String bucketName = "sxmy";
    private static final String ossAddress = "https://sxmy.oss-cn-qingdao.aliyuncs.com";
    /**
     *上传单个文件工具
     * @param mkdir
     * @param filePath
     * @param bytes
     * @throws IOException
     */
    public static void uploadFile(String mkdir, String filePath, byte[] bytes)throws IOException{
        OSSClient ossClient = MyOssClient.getOssClient();
        boolean exist = ossClient.doesObjectExist(bucketName,mkdir);
        if(exist){
            ossClient.deleteObject(bucketName,mkdir);
        }
        ossClient.putObject(bucketName,filePath,new ByteArrayInputStream(bytes));
        MyOssClient.shutdownOss();
    }


    public static void uploadFiles(String folder,String newName,MultipartFile [] files)throws IOException{

    }

    /**
     * 获取文件的url访问路径
     * @param fileName
     * @return
     */
    public static String getUrl(String fileName){
        OSSClient ossClient = MyOssClient.getOssClient();
        Calendar calendar = Calendar.getInstance();
        //有效期10年
        calendar.set(Calendar.YEAR,calendar.get(Calendar.YEAR)+100);
        Date date = calendar.getTime();
        Date expiration = new Date(date.getTime() + 3600*1000);
        URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
        return ossAddress+url.getFile();
    }
}
